from appserver import db_store
import traceback


class RoleWithUser(db_store.Model):
    __tablename__ = "roles_with_users"
    __bind_key__ = "main"

    # id=db_store.Column(db_store.Integer,primary_key=True)
    role_id = db_store.Column(db_store.Integer, db_store.ForeignKey("roles.id"), primary_key=True, nullable=False)
    user_id = db_store.Column(db_store.Integer, db_store.ForeignKey("users.id"), primary_key=True, nullable=False)

    def __repr__(self):
        return "<RoleWithUser %d+%d>" % (self.role_id, self.user_id)

    def save(self):
        if self.role_id is None:
            print("RoleWithUser save error: role_id cannot be empty")
            return -1
        if self.user_id is None:
            print("RoleWithUser save error: user_id cannot be empty")
            return -2
        try:
            db_store.session.add(self)
            db_store.session.commit()
            return 0
        except:
            print("table roles_with_users write error:\n---------------------------------\n%s\n-------------------------------" % (traceback.format_exc()))
            db_store.session.rollback()
            return -3

    def delete(self):
        try:
            db_store.session.delete(self)
            db_store.session.commit()
            return 0
        except:
            print("RoleWithUser delete error: %s" % (id, traceback.format_exc()))
            db_store.session.rollback()
            return -1

    @staticmethod
    def get_role_with_user_only(user_id, role_id):
        return RoleWithUser.query.filter_by(user_id=user_id, role_id=role_id).first()

# @staticmethod
# def get_role_with_user_only(user_id,role_id):
#     return RoleWithUser.query.filter_by(user_id=user_id,role_id=role_id).first()
#
    @staticmethod
    def get_role_with_user_by_user_id(user_id):
        return RoleWithUser.query.filter_by(user_id=user_id).all()
#
    # @staticmethod
    # def get_role_with_user_by_role_id(role_id):
    #     return RoleWithUser.query.filter_by(role_id=role_id).all()
#
